package com.zut.dao.impl;

import com.zut.dao.CourseDao;
import com.zut.entity.Course;
import com.zut.util.JdbcUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * 课程的持久层实现类： 通过sql操作课程表
 */
public class CourseDaoImpl implements CourseDao {

    //接收JdbcTemplate 工具对象
    private JdbcTemplate template = JdbcUtil.template;

    /**
     * 根据课程名称查询
     * @param cname
     * @return
     */
    @Override
    public Course findCourseByCname(String cname) {
        try {
           return template.queryForObject("select * from course where cname=?",new BeanPropertyRowMapper<>(Course.class),cname);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    /**
     * 添加课程
     * @param cname
     */
    @Override
    public void addCourse(String cname) {
        template.update("insert into course values (null,?)",cname);
    }

    /**
     * 查询所有课程
     * @return
     */
    @Override
    public List<Course> findAllCourse() {
        return template.query("select * from  course",new BeanPropertyRowMapper<>(Course.class));
    }

    /**
     * 模糊查询班级
     * @param s
     * @return
     */
    @Override
    public List<Course> findCourseLikeCname(String s) {
        return template.query("select * from course where cname like ?",new BeanPropertyRowMapper<>(Course.class),s);
    }

    /**
     * 根据编号修改课程名称
     * @param cid
     * @param newcname
     */
    @Override
    public void updateCourse(String cid, String newcname) {
        template.update("update course set cname=? where id=?",newcname,cid);
    }

    /**
     * 根据编号删除
     * @param cid
     */
    @Override
    public void deleteCourseById(String cid) {

        template.update("delete from course where id=?",cid);
    }

    /**
     * 根据教师编号查询课程
     * @param tid
     * @return
     */
    @Override
    public Course findCourseByTid(String tid) {
        try {
           return template.queryForObject("select * from course where id = (select cid from teacher where id=?)",new BeanPropertyRowMapper<>(Course.class),tid);
        }catch (EmptyResultDataAccessException e){
            return null;
        }

    }
}
